package com.example.arithmeticleetcode.leetcode.jan;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2021-01-19 09:34
 **/
public class Demo14 {

    public static void main(String[] args) {
        int[] nums = {2, 3, 4, 6, 8, 12};
        tupleSameProduct(nums);
    }

    public static int minCostConnectPoints(int[][] points) {
        int sum = 0;
        for (int i = 0; i < points.length; i++) {
            int temp = i;
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < points.length; j++) {
                if (i == j) continue;
                min = Math.min(Math.abs(points[temp][0] - points[j][0]) + Math.abs(points[temp][1] - points[j][1]), min);
            }
            sum += min;
        }
        return sum;
    }


    /**
     * 1726. 同积元组
     *
     * @param nums
     * @return
     */
    public static int tupleSameProduct(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length;
        for (int i = 0; i < len - 1; i++) {
            for (int j = i + 1; j < len; j++) {
                int num = nums[i] * nums[j];
                if (map.containsKey(num)) {
                    map.put(num, map.get(num) + 1);
                } else {
                    map.put(num, 1);
                }
            }
        }
        int res = 0;
        for (int num : map.values()) {
            if (num > 1) {
                res += (num - 1) * num / 2;
            }
        }
        return res * 8;
    }


    public static int tupleSameProduct2(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0, len = nums.length - 1; i < len; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int mult = nums[i] * nums[j];
                map.put(mult, map.getOrDefault(mult, 0) + 1);
            }
        }
        int ans = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() < 2) continue;
            ans += (entry.getValue() - 1) * entry.getValue();
        }
        return ans << 2;
    }
}
